<template>
  <!-- 添加或修改销售信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="订单编号" prop="projectId">
                <el-select v-model="form.projectId" filterable remote reserve-keyword placeholder="请输入订单编号"
                           :remote-method="search" :loading="projectLoading">
                  <el-option v-for="item in projectBaseInfoList" :key="item.code" @click.native="changePro(item)" :label="item.code" :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票单位" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择开票单位" filterable
                           clearable style="width: 100%">
                  <el-option v-for="dict in dict.type.goods_customer" ref="myselectCustomer"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="工程名称" prop="gongchengName">
                <el-input style="width: 100%;" v-model="form.gongchengName" placeholder="请输入工程名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="开票金额" prop="amount">
                <el-input-number style="width: 100%;" :precision="5" :min="0" v-model="form.amount"
                                 :max="form.taxRemain" placeholder="请输入开票金额"/>
                <span style="color: green;">订单金额：{{ form.contractMoney }}</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span style="color: red;">剩余开票：{{ form.taxRemain }}</span>

              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="开票明细" prop="files">
                <file-upload :limit="5" v-model="form.files"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>


<script>
import {addAction, getAction, getById, deleteAction, updateAction} from '@/api/manage'
import {updateGoodsSale} from '@/api/develop/goodsInvoiceBatch'
import request from '@/utils/request'
import {parseTime} from "@/utils/common";

export default {
  name: "GoodsInvoiceBatch",
  components: {
    //GoodsSaleListSelectForInvoice
  },
  dicts: ['company', 'goods_supplier', 'goods_customer'],
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "订单开票",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      columns: [],
      dataList: [],
      customerId: "",
      total: 0,
      ids: "",
      selectIds: "",
      selectIdsNew: [],
      // 表单校验
      rules: {
        projectId: [
          {required: true, message: "请选择项目信息", trigger: "blur"}
        ],
        customerId: [
          {required: true, message: "请选择客户信息", trigger: "blur"}
        ],
        amount: [
          {required: true, message: "开票金额不能为空", trigger: "blur"},
          {validator: this.validator, trigger: 'blur'}
        ],
        amountReal: [
          {required: true, message: "销售额不能为空", trigger: "blur"}
        ],
      },
      queryParams: {
        id: null,
        no: null,
        amount: null,
        amountReal: null,
        remaining: null,
        customerId: null,
        customerName: null,
        taxNo: null,
        invoiceDate: new Date(),
        invoiceCompany: null,
        fundCallback: null,
        backDate: null,
        drawerId: this.$store.getters.userId,
        //  drawerName: this.$store.getters.nickName,
        saleId: null,
        saleName: null,
        files: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      },
      url: {
        listBatch: '/goodsInvoice/goodsInvoice/listBatch/',
        proNames: '/projectBaseInfo/projectBaseInfo/prjNames',
      },
      orderInfo: {},
      proNameOptions: [],
      projectBaseInfoList:[],
      projectLoading:false,
    };
  },
  created() {
  },
  methods: {
    validator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('开票金额不能为0'));
      } else {
        callback();
      }
    },

    async search(queryString) {
      this.projectLoading = true;
      if (queryString) {
        try {
          let params = {
            // "pageSizeZero": true,
            "pageNum": 1,
            "pageSize": 20,
            "code": queryString

          };
          getAction("/projectBaseInfo/projectBaseInfo/listNotAllKp", params).then(response => {
            debugger
            this.projectBaseInfoList = response.rows;
            this.projectLoading = false;
          });

        } catch (error) {
          console.error('Error fetching data:', error);
          this.projectLoading = false;
        }
      } else {
        this.projectBaseInfoList = [];
        this.projectLoading = false;
      }
    },


    changePro(item) {
      let that = this;
      that.form.projectName = item.name;
      that.form.projectNo = item.code;
      that.$set(that.form, "customerId", item.customId);
      that.$set(that.form, "customerName", item.customName);
      that.$set(that.form, "amount", 0);
      that.$set(that.form, "taxRemain", item.taxRemain);
      that.$set(that.form, "contractMoney", item.contractMoney);
      that.$set(that.form, "taxNo", item.params.taxNo);
      that.$set(that.form, "saleName", item.saleName);
      that.$set(that.form, "saleId", item.saleId);
    },

    /** 查询项目信息列表 */
    initProDicts() {
      let that = this;
      getAction(that.url.proNames, {orderByColumn: "create_time", isAsc: "desc"}).then(res => {
        that.proNameOptions = res.data.nameList;
      })
    },

    showAddView(type) {
      this.reset();
      this.selectIds = "";
      this.open = true;
      this.loading = false;
      this.form.type = type;
      this.form.invoiceApplyDate = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      this.initProDicts();
    },


    selectCustomer(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectCustomer;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.customerName = arr[i].label;
            that.form.taxNo = arr[i].taxNo;
          }
        }
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsId: null,
        goodsName: null,
        goodsBrand: null,
        goodsUnitPrice: null,
        goodsCount: null,
        goodsTotalPrice: null,
        saleDate: null,
        supplierId: null,
        supplierName: null,
        customerId: null,
        customerName: null,
        invoiceCompany: "1",
        invoice: "0",
        invoiceId: null,
        invoiceNo: null,
        status: "0",
        fundCallback: "whx",
        receipt: null,
        saleId: null,
        saleName: null,
        invoiceApplyDate: null,
        invoiceDate: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId: this.$store.getters.deptId,
        deptName: this.$store.getters.deptName,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      that.$refs["form"].validate(valid => {
        if (valid) {
          if (that.form.type == 'xskp') {
            that.form.saleId = that.selectIds.toString();
          }
          that.form.amountReal = 0;
          that.form.pinRemain = 0;
          that.form.pinMoney = that.form.amount;
          that.form.remaining = that.form.amount - that.form.amountReal;
          updateGoodsSale(that.form).then(res => {
            that.$modal.msgSuccess(res.msg);
            if (res.code === 200) {
              this.open = false;
              that.form.amount = "";
              that.$emit('ok');
            }
          });

        }
      });
    },
  }
};
</script>
